Ultrasonic

An ultrasonic sensor can be used to measure distance to a solid object

A ultrasonic sensor measures distance by emitting an ultrasound signal and timing how long it takes for the signal to return. This is just like the method that bat's use to navigate!


Wire up

Connect the sensor as follows:

Wire up
Sensor Pico
Red 3V3
Black GND
Echo GP6 or another GP pin
Trig GP7 or another GP pin

Add the library

You need to add the HCSR04 library. Copy adafruit_hcsr04.py from the lib directory on github to the lib directory on the pico.

Add lib

Code

Write this code and download to the Pico.

See code on github
# Test ultrasonic distance sensor

import time
import board
import adafruit_hcsr04

# Create the sonar object connected to the given pins
sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.GP6, echo_pin=board.GP7)

# Display the distance measurement
while True:
    try:
        print(sonar.distance)
    except RuntimeError:
        print("Error")
    time.sleep(0.1)

Run the code and see the distance measurements in the output window. Move your hand in front of the sensor. The distance measurement should change accordingly.